<template>
  <div id="deviceHistoryContainer" style="width: 100%; height: 100%; padding: 10px 35px; box-sizing: border-box; position: relative; z-index: 10;">
    <div class="device-history-header" style="color: #0efcff; font-size: 1vw; margin: 0 8%; text-align: left; padding-bottom: 10px; border-bottom: 1px solid rgba(14, 252, 255, 0.3);">
      <i class="el-icon-data-analysis" style="margin-right: 8px;"></i>环境监测数据
    </div>
    <div id="devicePropertyList" style="color: #ffffff; font-size: 0.9vw; overflow-y: auto; max-height: calc(100% - 40px); height: calc(100% - 40px);">
      <!-- 设备属性数据将在这里展示 -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import {getAccessToken} from "@/utils/auth";

// 定义需要显示的传感器列表
const targetSensors = [5, 9, 13, 19, 17, 16];
const sensorNames = {
  1: '水质PH传感器',
  2: '水质EC传感器',
  3: '水质溶解氧传感器',
  4: '土壤温湿度传感器',
  5: '土壤温湿度传感器',
  6: '土壤温湿度传感器',
  7: '移动土壤温湿度传感器',
  8: '土壤氮磷钾传感器',
  9: '土壤氮磷钾传感器',
  10: '土壤氮磷钾传感器',
  11: '太移动土壤氮磷钾传感器',
  12: '土壤酸碱度传感器',
  13: '土壤酸碱度传感器',
  14: '土壤酸碱度传感器',
  15: '移动土壤酸碱度传感器',
  16: '空气温湿度传感器',
  17: '光照传感器',
  18: '光照传感器',
  19: '二氧化碳传感器'
};

// 存储上次传感器数据
let lastSensorDataList: any[] = [];

// 定时器引用
let refreshTimer: any = null;

// 当前摄像头引用
const currentCamera = ref<any>(null);

// 获取URL参数中的token
const getQueryParam = (name: string) => {
  // 使用正则表达式方法获取参数
  const url = window.location.href
  name = name.replace(/[\[\]]/g, '\\$&')
  const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
  const results = regex.exec(url)
  if (!results) return null
  if (!results[2]) return ''
  return decodeURIComponent(results[2].replace(/\+/g, ' '))
}

// 获取设备列表
const getDeviceList = async () => {
  try {

    // 首先尝试从URL参数获取token
    let token = getAccessToken()
    // let token = getQueryParam('token')
    // console.log('Token from URL:', token)

    // 如果URL中没有token，则尝试从localStorage获取
    if (!token) {
      const wsCache = new (window as any).WebStorageCache({
        storage: 'localStorage'
      })
      token = wsCache.get('ACCESS_TOKEN')
      // console.log('Token from localStorage:', token)
    }

    // 构建URL，使用VITE_BASE_URL环境变量
    const baseUrl = import.meta.env.VITE_BASE_URL || ''
    let url = `${baseUrl}/admin-api/eiot/device/page?pageNo=1&pageSize=100`
    // console.log('Request URL:', url)

    // 准备请求选项
    const requestOptions: any = {
      method: 'GET',
      headers: {}
    }

    // 如果有token，则添加到请求头中
    if (token) {
      requestOptions.headers['Authorization'] = `Bearer ${token}`
    }
    // console.log('Request options:', requestOptions)

    const response = await fetch(url, requestOptions)
    // console.log('Response received:', response)

    // 检查响应状态
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 获取响应文本
    const text = await response.text()
    // console.log('Response text:', text)

    // 检查返回的内容是否为HTML（登录页面）
    if (text.includes('<!DOCTYPE html') || text.includes('<html') || text.includes('login')) {
      // console.log('Response is HTML login page')
      return []
    }

    // 尝试解析JSON
    try {
      const result = JSON.parse(text)
      // console.log('Parsed result:', result)

      // 验证返回的数据结构
      if (result && result.code === 0 && result.data && Array.isArray(result.data.list)) {
        // console.log('Returning device list:', result.data.list)
        return result.data.list
      } else if (result && Array.isArray(result.list)) {
        // 兼容直接返回list的格式
        // console.log('Returning device list (compatibility mode):', result.list)
        return result.list
      } else {
        // console.error('返回的数据格式不正确:', result)
        return []
      }
    } catch (jsonError) {
      // console.error('解析JSON失败:', jsonError)
      throw new Error('API返回的数据不是有效的JSON格式')
    }
  } catch (error) {
    // console.error('获取设备列表失败:', error)
    return []
  }
}

// 获取设备属性
const getDeviceProperties = async (deviceId: string) => {
  try {
    // console.log('getDeviceProperties function called with deviceId:', deviceId)

    // 首先尝试从URL参数获取token
    // let token = getQueryParam('token')
    let token = getAccessToken()
    // console.log('Token from URL:', token)

    // 如果URL中没有token，则尝试从localStorage获取
    if (!token) {
      const wsCache = new (window as any).WebStorageCache({
        storage: 'localStorage'
      })
      token = wsCache.get('ACCESS_TOKEN')
      // console.log('Token from localStorage:', token)
    }

    // 构建URL，使用VITE_BASE_URL环境变量
    const baseUrl = import.meta.env.VITE_BASE_URL || ''
    let url = `${baseUrl}/admin-api/eiot/device/getDeviceWithProperty`
    // console.log('Request URL:', url)

    // 准备请求选项
    const requestOptions: any = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ deviceId: deviceId })
    }
    // console.log('Request body:', { deviceId: deviceId })

    // 如果有token，则添加到请求头中
    if (token) {
      requestOptions.headers['Authorization'] = `Bearer ${token}`
    }
    // console.log('Request options:', requestOptions)

    const response = await fetch(url, requestOptions)
    // console.log('Response received:', response)

    // 检查响应状态
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 获取响应文本
    const text = await response.text()
    // console.log('Response text:', text)

    // 检查返回的内容是否为HTML（登录页面）
    if (text.includes('<!DOCTYPE html') || text.includes('<html') || text.includes('login')) {
      // console.log('Response is HTML login page')
      return null
    }

    // 尝试解析JSON
    try {
      const result = JSON.parse(text)
      // console.log('Parsed result:', result)

      // 验证返回的数据结构
      if (result && result.code === 0) {
        // console.log('Returning device properties:', result.data)
        return result.data
      } else if (result && result.code !== 0) {
        // console.error('API返回错误:', result.msg || '未知错误')
        return null
      } else {
        // console.error('返回的数据格式不正确:', result)
        return null
      }
    } catch (jsonError) {
      console.error('解析JSON失败:', jsonError)
      // throw new Error('API返回的数据不是有效的JSON格式')
    }
  } catch (error) {
    // console.error('获取设备属性失败:', error)
    return null
  }
}

// 获取指定传感器的最新数据
const getSensorData = async (sensor: number) => {
  try {
    let token = getAccessToken()

    if (!token) {
      const wsCache = new (window as any).WebStorageCache({
        storage: 'localStorage'
      })
      token = wsCache.get('ACCESS_TOKEN')
    }

    const baseUrl = import.meta.env.VITE_BASE_URL || ''
    const url = `${baseUrl}/admin-api/eiot/device/deviceLogs/list`

    // 获取设备列表以获取第一个设备的ID
    const devices = await getDeviceList()
    if (!Array.isArray(devices) || devices.length === 0) {
      throw new Error('未找到设备')
    }
    const deviceId = devices[0].id

    const requestOptions: any = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        deviceId: deviceId,
        sensor: sensor,
        pageNo: 1,
        pageSize: 100
      })
    }

    if (token) {
      requestOptions.headers['Authorization'] = `Bearer ${token}`
    }

    const response = await fetch(url, requestOptions)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const text = await response.text()

    if (text.includes('<!DOCTYPE html') || text.includes('<html') || text.includes('login')) {
      return null
    }

    try {
      const result = JSON.parse(text)
      // 检查返回的数据结构
      if (result && result.code === 0 && result.data && Array.isArray(result.data.list) && result.data.list.length > 0) {
        // 在返回的数据列表中查找包含指定传感器的数据条目
        for (const item of result.data.list) {
          if (item.data && item.data.sensor === sensor) {
            // 返回匹配传感器的数据项
            return {
              value: item.data,
              createTime: new Date(item.time).toLocaleString()
            };
          }
        }
        // 如果没有找到匹配的数据，返回null
        return null;
      } else {
        return null;
      }
    } catch (jsonError) {
      console.error('解析JSON失败:', jsonError)
      return null
    }
  } catch (error) {
    console.error(`获取传感器${sensor}数据失败:`, error)
    return null
  }
}

// 处理摄像头切换事件
const handleCameraChange = (camera: any) => {
  // 更新当前摄像头
  currentCamera.value = camera;

  // 获取当前摄像头关联的传感器编号，过滤掉为null的值
  const cameraSensors = [
    camera.cgqNumber1,
    camera.cgqNumber2,
    camera.cgqNumber3,
    camera.cgqNumber4,
    camera.cgqNumber5
  ].filter(sensor => sensor !== null);

  // 如果有传感器编号，则加载对应数据
  if (cameraSensors.length > 0) {
    // 显示摄像头关联的传感器数据
    displaySensorDataForCamera(cameraSensors);
  } else {
    // 如果没有关联传感器，显示默认数据
    displayDefaultSensorData();
  }

  // 重启定时器以确保新数据持续更新
  restartAutoRefresh();
}

// 根据摄像头关联的传感器显示数据
async function displaySensorDataForCamera(sensorIds) {
  if (sensorIds.length > 0) {
    // 直接获取这些传感器的数据
    console.log(sensorIds)
    const sensorDataPromises = sensorIds.map(sensorId => getSensorData(sensorId));
    const sensorDataList = await Promise.all(sensorDataPromises);

    // 过滤掉空数据
    const validSensorDataList = sensorDataList.filter(data => data !== null);
    console.log(validSensorDataList)
    // 如果有任何有效的传感器数据
    if (validSensorDataList.length > 0) {
      // 显示所有有效传感器的数据
      const container = document.getElementById('devicePropertyList');
      if (container) {
        // 显示传感器数据
        displaySensorData(validSensorDataList);
      }
    } else {
      // 如果没有有效数据，显示默认数据
      console.log("显示默认数据")
      displayDefaultSensorData();
    }
  }
}

// 显示默认传感器数据
const displayDefaultSensorData = async () => {
  // 获取所有指定传感器的数据
  const sensorDataPromises = targetSensors.map(sensor => getSensorData(sensor))
  const sensorDataList = await Promise.all(sensorDataPromises)

  // 更新上次数据缓存 - 只有当新数据存在时才更新
  for (let i = 0; i < sensorDataList.length; i++) {
    if (sensorDataList[i] !== null) {
      lastSensorDataList[i] = sensorDataList[i];
    }
  }

  // 使用上次数据填充空数据
  const displayDataList = sensorDataList.map((data, index) =>
    data !== null ? data : lastSensorDataList[index]
  );

  // 显示传感器数据
  displaySensorData(displayDataList);
}

// 显示传感器数据的通用方法
const displaySensorData = (displayDataList: any[]) => {
  const container = document.getElementById('devicePropertyList')
  if (!container) return

  // 定义字段映射和单位
  const fieldMapping: any = {
    'soil_temp': '土壤温度',
    'soil_humi': '土壤湿度',
    'soil_n': 'N',
    'soil_p': 'P',
    'soil_k': 'K',
    'soil_ph': '土壤pH',
    'air_temp': '空气温度',
    'air_humi': '空气湿度',
    'ghi': '辐射',
    'co2': 'CO2',
    'water_ph': '水pH',
    'water_ec': '水EC',
    'light': '光照',
    'water_do': '溶解氧'
  };

  const fieldUnits: any = {
    'soil_temp': '°C',
    'soil_humi': '%',
    'soil_n': 'mg/kg',
    'soil_p': 'mg/kg',
    'soil_k': 'mg/kg',
    'soil_ph': '',
    'air_temp': '°C',
    'air_humi': '%',
    'ghi': 'W/㎡',
    'co2': 'ppm',
    'water_ph': '',
    'water_ec': 'ms/cm',
    'light': '',
    'water_do': 'mg/L',
  };

  // 图标映射
  const sensorIcons: any = {
    1: '🧪',
    2: '🧪',
    3: '🧪',
    4: '🌱',
    5: '🌱',
    6: '🌱',
    7: '🌱',
    8: '🌿',
    9: '🌿',
    10: '🌿',
    11: '🌿',
    12: '🍃',
    13: '🍃',
    14: '🍃',
    15: '🍃',
    16: '💨',
    17: '☀️',
    18: '☀️',
    19: '💨'
  };

  let html = '<div style="display: flex; gap: 15px; flex-wrap: nowrap; overflow-x: auto; height: 100%;">'
  html += '<div style="flex: 1; display: flex; gap: 15px; min-width: 0; height: 100%;">'

  // 动态生成传感器数据显示区域
  html += '<div style="display: flex; gap: 15px; flex-wrap: nowrap; width: 100%; height: 100%;">'

  // 遍历所有传入的传感器数据，只显示有数据的传感器
  displayDataList.forEach((sensorData, index) => {
    if (sensorData && sensorData.value) {
      // 获取传感器编号
      const sensorNumber = sensorData.value.sensor;
      
      // 查找传感器名称（如果在sensorNames中定义）
      const sensorName = sensorNames[sensorNumber] || `传感器${sensorNumber}`;
      const sensorIcon = sensorIcons[sensorNumber] || '📊';
      
      let dataHtml = '';
      let fieldCount = 0;
      
      Object.keys(sensorData.value).forEach(key => {
        if (key !== 'sensor' && key !== 'gateway') {
          let displayName = fieldMapping[key] || key;
          let unit = fieldUnits[key] || '';
          dataHtml += `<div style="margin-bottom: 5px; font-size: 0.8vw;"><span style="display: inline-block; min-width: 80px;">${displayName}:</span> <span>${sensorData.value[key]}${unit}</span></div>`;
          fieldCount++;
        }
      });

      html += `
        <div style="background: linear-gradient(135deg, rgba(14, 252, 255, 0.1) 0%, rgba(14, 252, 255, 0.05) 100%); 
                    padding: 10px; 
                    border-radius: 8px; 
                    border: 1px solid rgba(14, 252, 255, 0.3); 
                    font-size: 0.9vw; 
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
                    backdrop-filter: blur(10px);
                    transition: transform 0.3s ease, box-shadow 0.3s ease;
                    min-width: 0;
                    position: relative;
                    flex: 1 1 auto;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    height: 100%;
                    display: flex;
                    flex-direction: column;">
          <div style="font-weight: bold; 
                      margin-bottom: 8px; 
                      font-size: 1vw; 
                      color: #0efcff;
                      display: flex;
                      align-items: center;
                      padding-bottom: 5px;
                      border-bottom: 1px solid rgba(14, 252, 255, 0.3);
                      flex-shrink: 0;">
            <span style="margin-right: 8px; font-size: 1.1vw;">${sensorIcon}</span>
            <span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${sensorName}</span>
          </div>
          <div style="margin-left: 5px; padding: 5px 0; flex-grow: 1; overflow-y: auto;">
            ${dataHtml}
          </div>
          <div style="position: absolute; bottom: 5px; right: 10px; font-size: 0.7vw; color: rgba(255, 255, 255, 0.7);">
            共 ${fieldCount} 项参数
          </div>
        </div>
      `
    }
    // 无数据的传感器不显示
  });

  html += '</div>' // 传感器数据网格结束
  html += '</div>' // 传感器数据显示区域结束
  html += '</div>' // 整体flex容器结束

  container.innerHTML = html
}

// 显示传感器数据（原始方法，用于定时刷新）
const displaySensorDataOriginal = async () => {
  const container = document.getElementById('devicePropertyList')
  if (!container) return

  try {
    // 获取所有指定传感器的数据
    const sensorDataPromises = targetSensors.map(sensor => getSensorData(sensor))
    const sensorDataList = await Promise.all(sensorDataPromises)

    // 更新上次数据缓存 - 只有当新数据存在时才更新
    for (let i = 0; i < sensorDataList.length; i++) {
      if (sensorDataList[i] !== null) {
        lastSensorDataList[i] = sensorDataList[i];
      }
    }

    // 使用上次数据填充空数据
    const displayDataList = sensorDataList.map((data, index) =>
      data !== null ? data : lastSensorDataList[index]
    );

    // 显示传感器数据
    displaySensorData(displayDataList);
  } catch (error) {
    console.error('显示传感器数据失败:', error)
    if (container) {
      container.innerHTML = '<div>加载传感器数据失败: ' + (error as Error).message + '</div>'
    }
  }
}

// 显示设备属性数据
const displayDeviceProperties = (device: any, properties: any) => {
  const container = document.getElementById('devicePropertyList')
  if (!container) return

  // 检查设备数据
  if (!device) {
    container.innerHTML = '<div>设备数据无效</div>'
    return
  }

  // 隐藏设备名称显示
  let html = '' // 移除设备名称显示

  // 检查属性数据
  if (properties && properties.identifier2property) {
    // 过滤掉 sensor 和 gateway 属性
    const filteredProperties: any = {}
    Object.keys(properties.identifier2property).forEach(key => {
      const prop = properties.identifier2property[key]
      // 检查属性是否包含 sensor 或 gateway 关键字（不区分大小写）
      if (prop && prop.name &&
        !prop.name.toLowerCase().includes('sensor') &&
        !prop.name.toLowerCase().includes('gateway')) {
        filteredProperties[key] = prop
      }
    })

    // 分类属性：空气、光照、土壤养分、土壤环境、水质
    const airProperties: any = {}
    const lightProperties: any = {}
    const soilNutrientProperties: any = {}
    const soilEnvironmentProperties: any = {}
    const waterProperties: any = {}

    Object.keys(filteredProperties).forEach(key => {
      const prop = filteredProperties[key]
      if (prop && prop.name) {
        const name = prop.name
        // 空气相关属性
        if (name.includes('空气') ||
          (name.includes('湿度') && !name.includes('土壤')) ||
          (name.includes('温度') && !name.includes('土壤')) ||
          name.includes('二氧化碳') ||
          name.includes('CO2') ||
          name.includes('大气')) {
          airProperties[key] = prop
        }
        // 光照相关属性
        else if (name.includes('光照') ||
          name.includes('辐射') ||
          name.includes('光强')) {
          lightProperties[key] = prop
        }
        // 土壤养分相关属性
        else if (name.includes('氮') ||
          name.includes('磷') ||
          name.includes('钾') ||
          name.toUpperCase().includes('N') ||
          (name.toUpperCase().includes('P') && !name.includes('H')) ||
          name.toUpperCase().includes('K') ||
          name.includes('养分')) {
          soilNutrientProperties[key] = prop
        }
        // 土壤环境相关属性（包括土壤温度、土壤湿度和土壤PH）
        else if (name.includes('土壤')) {
          soilEnvironmentProperties[key] = prop
        }
        // 水质相关属性（包括水、水PH、酸碱相关属性，但不包括土壤PH）
        else if (name.includes('水') ||
          name.includes('PH') ||
          name.includes('酸碱')) {
          waterProperties[key] = prop
        }
        // 其他属性暂时不显示
      }
    })

    // 一行展示五个类别，每个类别等宽
    html += '<div style="display: flex; gap: 10px;">'

    // 空气数据列
    html += '<div style="flex: 1;">'
    html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">💨 空气数据</h3>'
    html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">'

    const airPropertyKeys = Object.keys(airProperties)
    if (airPropertyKeys.length > 0) {
      airPropertyKeys.forEach(key => {
        const prop = airProperties[key]
        if (prop) {
          let displayName = prop.name || key
          let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : ''

          let icon = '🔹' // 默认图标
          if (displayName.includes('湿度')) {
            icon = '💧'
          } else if (displayName.includes('温度')) {
            icon = '🌡️'
          } else if (displayName.includes('二氧化碳') || displayName.includes('CO2')) {
            icon = '💨'
          }

          html += `
            <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
              <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
            </div>
          `
        }
      })
    } else {
      html += '<div style="grid-column: span 1;">暂无空气数据</div>'
    }

    html += '</div>' // 空气数据网格结束
    html += '</div>' // 空气数据区域结束

    // 光照数据列
    html += '<div style="flex: 1;">'
    html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">☀️ 光照数据</h3>'
    html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">'

    const lightPropertyKeys = Object.keys(lightProperties)
    if (lightPropertyKeys.length > 0) {
      lightPropertyKeys.forEach(key => {
        const prop = lightProperties[key]
        if (prop) {
          let displayName = prop.name || key
          let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : ''

          let icon = '☀️' // 默认图标为太阳
          if (displayName.includes('辐射')) {
            icon = '🔥' // 辐射属性使用火焰图标
          }

          html += `
            <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
              <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
            </div>
          `
        }
      })
    } else {
      html += '<div style="grid-column: span 1;">暂无光照数据</div>'
    }

    html += '</div>' // 光照数据网格结束
    html += '</div>' // 光照数据区域结束

    // 土壤养分数据列
    html += '<div style="flex: 1;">'
    html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">🌿 土壤养分</h3>'
    html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">'

    const soilNutrientPropertyKeys = Object.keys(soilNutrientProperties)
    if (soilNutrientPropertyKeys.length > 0) {
      soilNutrientPropertyKeys.forEach(key => {
        const prop = soilNutrientProperties[key]
        if (prop) {
          let displayName = prop.name || key
          let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : ''

          let icon = '🌿' // 默认图标为植物
          if (displayName.includes('氮') || displayName.toUpperCase().includes('N')) {
            icon = '🌿' // 氮元素 - 用植物符号表示
          } else if (displayName.includes('磷') || (displayName.toUpperCase().includes('P') && !displayName.includes('H'))) {
            icon = '🦴' // 磷元素 - 用骨头符号表示
          } else if (displayName.includes('钾') || displayName.toUpperCase().includes('K')) {
            icon = '🍌' // 钾元素 - 用香蕉符号表示
          }

          html += `
            <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
              <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
            </div>
          `
        }
      })
    } else {
      html += '<div style="grid-column: span 1;">暂无土壤养分数据</div>'
    }

    html += '</div>' // 土壤养分数据网格结束
    html += '</div>' // 土壤养分数据区域结束

    // 土壤环境数据列
    html += '<div style="flex: 1;">'
    html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">🌱 土壤环境</h3>'
    html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">'

    const soilEnvironmentPropertyKeys = Object.keys(soilEnvironmentProperties)
    if (soilEnvironmentPropertyKeys.length > 0) {
      soilEnvironmentPropertyKeys.forEach(key => {
        const prop = soilEnvironmentProperties[key]
        if (prop) {
          let displayName = prop.name || key
          let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : ''

          let icon = '🌱' // 默认图标为幼苗
          if (displayName.includes('湿度')) {
            icon = '💧'
          } else if (displayName.includes('温度')) {
            icon = '🌡️'
          } else if (displayName.includes('PH')) {
            icon = '🧪' // 土壤PH使用试管图标表示酸碱度
          }

          html += `
            <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
              <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
            </div>
          `
        }
      })
    } else {
      html += '<div style="grid-column: span 1;">暂无土壤环境数据</div>'
    }

    html += '</div>' // 土壤环境数据网格结束
    html += '</div>' // 土壤环境数据区域结束

    // 水质数据列
    html += '<div style="flex: 1;">'
    html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">💧 水质数据</h3>'
    html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">'

    const waterPropertyKeys = Object.keys(waterProperties)
    if (waterPropertyKeys.length > 0) {
      waterPropertyKeys.forEach(key => {
        const prop = waterProperties[key]
        if (prop) {
          let displayName = prop.name || key
          let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : ''

          let icon = '💧' // 默认图标为水滴
          if (displayName.includes('PH') || displayName.includes('酸碱')) {
            icon = '🧪' // 水PH使用试管图标表示酸碱度
          }

          html += `
            <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
              <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
            </div>
          `
        }
      })
    } else {
      html += '<div style="grid-column: span 1;">暂无水质数据</div>'
    }

    html += '</div>' // 水质数据网格结束
    html += '</div>' // 水质数据区域结束

    html += '</div>' // 整体flex容器结束

  } else {
    html += '<div>暂无属性数据</div>'
  }

  container.innerHTML = html
}

// 重启定时刷新
const restartAutoRefresh = () => {
  // 停止当前定时器
  stopAutoRefresh();
  // 开始新的定时刷新
  startAutoRefresh();
}

// 开始定时刷新
function startAutoRefresh() {
  // 先清除现有的定时器
  stopAutoRefresh();

  // 设置新的定时器
  refreshTimer = setInterval(() => {
    if (currentCamera.value) {
      // 获取当前摄像头关联的传感器编号，过滤掉为null的值
      const cameraSensors = [
        currentCamera.value.cgqNumber1,
        currentCamera.value.cgqNumber2,
        currentCamera.value.cgqNumber3,
        currentCamera.value.cgqNumber4,
        currentCamera.value.cgqNumber5
      ].filter(sensor => sensor !== null);

      if (cameraSensors.length > 0) {
        // 显示摄像头关联的传感器数据
        displaySensorDataForCamera(cameraSensors);
      } else {
        // 显示默认数据
        displayDefaultSensorData();
      }
    } else {
      // 如果没有当前摄像头，加载默认数据
      // loadSensorData(sensorId);
    }
  }, 5000); // 5秒刷新一次
}

// 停止定时刷新
function stopAutoRefresh() {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
}

// 加载第一个设备的属性数据
const loadFirstDeviceProperties = async () => {
  try {
    // 获取设备列表
    const devices = await getDeviceList()
    const container = document.getElementById('devicePropertyList')
    if (!container) return

    if (!Array.isArray(devices) || devices.length === 0) {
      container.innerHTML = '<div>暂无设备数据</div>'
      return
    }

    // 直接加载第一个设备的属性
    const firstDevice = devices[0]
    const properties = await getDeviceProperties(firstDevice.id)
    displayDeviceProperties(firstDevice, properties)
  } catch (error) {
    console.error('加载设备属性数据失败:', error)
    const container = document.getElementById('devicePropertyList')
    if (container) {
      container.innerHTML = '<div>加载设备数据失败: ' + (error as Error).message + '</div>'
    }
  }
}

// 在组件挂载时暴露handleCameraChange方法供父组件调用
defineExpose({
  handleCameraChange
})

onMounted(() => {
  // 加载默认传感器数据
  displayDefaultSensorData();
  // 开始自动刷新传感器数据
  startAutoRefresh();
})

onUnmounted(() => {
  // 组件销毁时停止自动刷新
  stopAutoRefresh();
})
</script>

<style scoped>
/* 样式已在模板中内联定义 */
</style>
